<template>
  <div class="flex-row align-items space-between">
    <el-input :value="currentValue" :placeholder="placeholder ? placeholder : label" @input="onInputEvent" />
    <el-button
      class="sendCode"
      :type="getCodeBtnDisable ? 'info' : 'primary'"
      :disabled="getCodeBtnDisable"
      @click="getCode"
      >{{ codeBtnWord }}</el-button
    >
  </div>
</template>

<script>
import { ruleTel } from '@/utils/validate.js'
export default {
  // eslint-disable-next-line vue/require-prop-types
  props: ['placeholder', 'label', 'name', 'value', 'date', 'formData', 'phoneProps'],
  data() {
    return {
      currentValue: this.value,
      codeBtnWord: '获取验证码',
      waitTime: 60
    }
  },
  computed: {
    // 用于校验手机号码格式是否正确
    phoneNumberStyle() {
      if (this.formData[this.phoneProps].length === 11) {
        return true
      }
      return false
    },
    // 控制获取验证码按钮是否可点击
    getCodeBtnDisable: {
      get() {
        if (this.waitTime === 60) {
          if (this.formData[this.phoneProps]) {
            return false
          }
          return true
        }
        return true
      },
      // 注意：因为计算属性本身没有set方法，不支持在方法中进行修改，而下面我要进行这个操作，所以需要手动添加
      set() {}
    }
  },
  watch: {
    value(val) {
      this.currentValue = val
    }
  },
  methods: {
    onInputEvent(value) {
      this.$emit('input', this.name, value)
    },
    getCode() {
      if (this.phoneNumberStyle) {
        this.api
          .SendVerifRe({
            phone: this.formData[this.phoneProps]
          })
          .then(res => {
            this.$message({ type: 'success', message: '发送成功!' })
          })
        // 因为下面用到了定时器，需要保存this指向
        const that = this
        that.waitTime--
        that.getCodeBtnDisable = true
        this.codeBtnWord = `${this.waitTime}s 后重新获取`
        const timer = setInterval(function() {
          if (that.waitTime > 1) {
            that.waitTime--
            that.codeBtnWord = `${that.waitTime}s 后重新获取`
          } else {
            clearInterval(timer)
            that.codeBtnWord = '获取验证码'
            that.getCodeBtnDisable = false
            that.waitTime = 60
          }
        }, 1000)
      } else {
        this.$message({ type: 'info', message: '请输入正确手机号！' })
      }
    }
  }
}
</script>
<style scoped>
.sendCode {
  /* height: 40px;
  background: #1492ff;
  border-radius: 0.08rem;
  line-height: 0.32rem;
  color: rgba(255, 255, 255, 1);
  line-height: 40px; */
}
.disabled-style {
  background-color: rgba(242, 246, 252, 1);
  color: #1492ff;
  border: none;
  font-size: 0.32rem;
}
</style>
